<template>
    <n-card :bordered="false" class="proCard">
        <BasicForm @register="register" @submit="handleSubmit">
            <template #chanName="{ model, field }">
                <n-input v-model:value="model[field]" clearable placeholder="请输入渠道昵称" />
            </template>
        </BasicForm>

        <BasicTable ref="actionRef" :columns="columns" :row-key="(row) => row.id" :request="loadDataTable"  :scroll-x="2048">
            <template #toolbar>
                <n-button type="primary" @click="reloadTable">刷新数据</n-button>
            </template>
        </BasicTable>
    </n-card>
</template>
  
<script lang="ts" setup>
import { reactive, ref, unref } from 'vue';
import * as XLSX from 'xlsx';
import { BasicTable } from '@/components/Table';
import { BasicForm, FormSchema, useForm } from '@/components/Form/index';
import { columns } from './columns';
import { getChanPlayer } from '@/api/player/playerManage';
const actionRef = ref();
const schemas: FormSchema[] = [
    {
      field: 'chanName',
      component: 'NInput',
      label: '渠道昵称',
      componentProps: {
        placeholder: '渠道昵称',
        onInput: (e: any) => {
          console.log(e);
        },
      },
      slot: 'chanName',
    },
];

const [register, {  }] = useForm({
    gridProps: { cols: '1 s:1 m:2 l:3 xl:4 2xl:4' },
    labelWidth: 120,
    schemas,
});

const formParams = reactive({
    chanName: '',
});


function handleSubmit(values: Recordable) {
    console.log('handle', values);
    let tempParams = unref(formParams);
    Object.assign(tempParams, values);
    reloadTable();
}

function reloadTable() {
    actionRef.value.reload();
}

const loadDataTable = async (res) => {
    const param = { ...formParams, ...res };
    const data = await getChanPlayer(param);
    if(data.total > 0){
        exportToExcel(data.all);
    }
    return data;
};

const exportToExcel = (tableData) => {
    // 创建工作簿
    const workbook = XLSX.utils.book_new();
    // 将数据转换为工作表
    const worksheet = XLSX.utils.json_to_sheet(tableData);
    // 将工作表添加到工作簿
    XLSX.utils.book_append_sheet(workbook, worksheet, 'Sheet1');
    // 每列不同宽度px
    let wscols = [
      { wch: 14 },
      { wch: 14 },
      { wch: 20 },
      { wch: 18 },
      { wch: 14 },
      { wch: 18 },
      { wch: 14 },
      { wch: 14 },
    ];
    worksheet['!cols'] = wscols;
    var date = new Date(Date.now());
    var Y = date.getFullYear() + '-';
    var M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-';
    var D = (date.getDate() < 10 ? '0' + date.getDate() : date.getDate()) + ' ';
    var strDate = Y + M + D;
    XLSX.writeFile(workbook, `渠道玩家充值表(${strDate}).xlsx`);
}

</script>
  
  <style lang="less" scoped></style>
  